<?php

class PaypalsController extends AppController {

    var $name = 'Paypals';
    var $helpers = array('Form', 'Javascript', 'Session', 'Html', 'Form', 'Ajax', 'Text');
    var $components = array('Session', 'Auth', 'Cookie', 'RequestHandler');
    var $uses = array('User');

    function beforeFilter() {
        parent::beforeFilter();
    }

    function check_paypal_user() {
        echo __METHOD__;
        ini_set('track_errors', true);
        $url = trim('https://api-3t.sandbox.paypal.com/nvp');
        $body_data = array('USER' => "sbapi_1287090601_biz_api1.paypal.com", //TODO
            'PWD' => "1287090610",
            'SIGNATURE' => "ANFgtzcGWolmjcm5vfrf07xVQ6B9AsoDvVryVxEQqezY85hChCfdBMvY", //TODO
            'RETURNURL' => "http://wondere.com/Paypals/Paypal_authorization", //TODO
            'CANCELURL' => "http://wondere.com/Paypals/paypal_cancel", //TODO
            'LOGOUTURL' => "http://wondere.com/Paypals/logout_return", //TODO
            'VERSION' => "3.300000",
            'SERVICENAME1' => 'Name',
            'SERVICEDEFREQ1' => 'Required',
            'SERVICENAME2' => 'Email',
            'SERVICEDEFREQ2' => 'Required',
            'METHOD' => "SetAuthFlowParam"
        );
        $body_data = http_build_query($body_data, '', chr(38));
        try {
            $params = array(
                'http' => array(
                    'method' => "POST",
                    'Content-language' => 'en',
                    'Content-Type' => "application/x-www-form-urlencoded",
                    'content' => $body_data
                )
            );
            $ctx = stream_context_create($params);

            $fp = @fopen($url, 'r', false, $ctx);

            $response = stream_get_contents($fp);
            if ($response === false) {
                throw new Exception("php error message = " . "$php_errormsg");
            }
            fclose($fp);
            $key = explode("&", $response);
            $payPalURL = "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_account-authenticate-login&" . str_replace("TOKEN", "token", htmlspecialchars(urldecode($key[0])));
            If ($key[3] == 'ACK=Success') {
                echo '<meta http-equiv="refresh" content="0;url=' . $payPalURL . '">';
                exit;
            } else {
                echo 'ERROR Code: "' . str_replace("L_ERRORCODE0=", "", htmlspecialchars(urldecode($key[5]))) . '"<br/> Error Long Message: "' . str_replace("L_LONGMESSAGE0=", "", htmlspecialchars(urldecode($key[7]))) . '"';
                exit;
            }
        } catch (Exception $e) {
            echo 'Message: ||' . $e->getMessage() . '||';
        }
    }

    function logout_return() {
        echo __METHOD__;
        $this->redirect('/');
        echo "<pre>";
        print_r($_REQUEST);
        echo "</pre>";
        exit;
    }

    function PPHttpPost($methodName_, $nvpStr_) {
        echo __METHOD__;
        $environment = "sandbox";
        // Set up your API credentials, PayPal end point, and API version.
        $API_UserName = urlencode('vineet_1284714732_biz_api1.gmail.com');
        $API_Password = urlencode('1284714740');
        $API_Signature = urlencode('ACUe-E7Hjxmeel8FjYAtjnx-yjHAAfs5mA94HbT8CgYe.8571qB15LiS ');
        $API_Endpoint = "https://api-3t.paypal.com/nvp";
        if ("sandbox" === $environment || "beta-sandbox" === $environment) {
            $API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
        }
        $version = urlencode('51.0');
        // Set the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // Turn off the server and peer verification (TrustManager Concept).
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // Set the API operation, version, and API signature in the request.
        $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

        // Set the request as a POST FIELD for curl.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

        // Get response from the server.
        $httpResponse = curl_exec($ch);

        if (!$httpResponse) {
            exit("$methodName_ failed: " . curl_error($ch) . '(' . curl_errno($ch) . ')');
        }

        // Extract the response details.
        $httpResponseAr = explode("&", $httpResponse);

        $httpParsedResponseAr = array();
        foreach ($httpResponseAr as $i => $value) {
            $tmpAr = explode("=", $value);
            if (sizeof($tmpAr) > 1) {
                $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
            }
        }

        if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
            exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
        }

        return $httpParsedResponseAr;
    }

    function paypal_cancel() {
        echo __METHOD__;
        echo "Cancel";
        pr($_REQUEST);
        exit;
    }

    function Paypal_authorization($token = "") {
        echo __METHOD__;
        $token = $_REQUEST['token'];
        ini_set('track_errors', true);
        $url = trim('https://api-3t.sandbox.paypal.com/nvp');
        $body_data = array('USER' => "sbapi_1287090601_biz_api1.paypal.com", //TODO
            'PWD' => "1287090610",
            'SIGNATURE' => "ANFgtzcGWolmjcm5vfrf07xVQ6B9AsoDvVryVxEQqezY85hChCfdBMvY", //TODO
            'VERSION' => "3.300000",
            "TOKEN" => $token,
            'METHOD' => "GetAuthDetails"
        );
        $body_data = http_build_query($body_data, '', chr(38));
        try {
            $params = array(
                'http' => array(
                    'method' => "POST",
                    'content' => $body_data
                )
            );
            $ctx = stream_context_create($params);
            $fp = @fopen($url, 'r', false, $ctx);
            $response = stream_get_contents($fp);
            if ($response === false) {
                throw new Exception("php error message = " . "$php_errormsg");
            }
            @fclose($fp);
            $key = explode("&", $response);
            $payPalURL = "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_account-authenticate-logout&&TOKEN=" . $token . "";
            If ($key[6] == 'ACK=Success') {
                /* Details will be saved in amazon authorised user */
                $PAYERID = str_replace('PAYERID=', '', $key[0]);

                $first_name = str_replace('FIRSTNAME=', '', $key[1]);
                $last_name = str_replace('LASTNAME=', '', $key[2]);

                $EMAIL = str_replace('EMAIL=', '', $key[3]);

                $this->data['Paypal']['user_id'] = $user_id = $this->Session->read('Auth.User.id');

                $this->data['Paypal']['paypal_email'] = htmlspecialchars(urldecode($EMAIL));

                $this->data['Paypal']['last_name'] = htmlspecialchars(urldecode($last_name));

                $this->data['Paypal']['first_name'] = htmlspecialchars(urldecode($first_name));

                $this->data['Paypal']['tokenID'] = htmlspecialchars(urldecode($PAYERID));

                if (isset($this->data['Paypal']) and sizeof($this->data['Paypal'])) {
                    $check_exist_entry = $this->Paypal->find('first', array(
                        'conditions' => 'Paypal.paypal_email="' . $this->data['Paypal']['paypal_email'] . '"
										   and Paypal.last_name="' . $this->data['Paypal']['last_name'] . '"
										   and Paypal.first_name="' . $this->data['Paypal']['first_name'] . '"'));
                    //pr($check_exist_entry);					   
                    //exit;
                    if (isset($check_exist_entry) and ($check_exist_entry)) {
                        $this->Session->setFlash('These Account Details are already Saved');
                        $this->redirect(array(
                            'controller' => 'users',
                            'action' => 'dashboard'
                        ));
                    } else {
                        $this->data['Paypal']['active'] = 1; // For verified Account User 	   
                        $this->Paypal->Save($this->data['Paypal']);
                        echo '<meta http-equiv="refresh" content="0;url=' . $payPalURL . '">';
                        exit;
                    }
                } else {
                    $this->Session->setFlash('Your Paypal Payment Details is not Received.');
                    $this->redirect(array(
                        'action' => 'dashboard',
                        'controller' => 'users'
                    ));
                }
            } else {
                $message = 'ERROR Code: "' . str_replace("L_ERRORCODE0=", "", htmlspecialchars(urldecode($key[5]))) . '"<br/> Error Long Message: "' . str_replace("L_LONGMESSAGE0=", "", htmlspecialchars(urldecode($key[7]))) . '"';
                $this->Session->setFlash('' . $message . '');
                $this->redirect(array(
                    'action' => 'dashboard',
                    'controller' => 'users'
                ));
            }
        } catch (Exception $e) {
            $message = 'Message: ||' . $e->getMessage() . '||';
            $this->Session->setFlash('' . $message . '');
            $this->redirect(array(
                'action' => 'dashboard',
                'controller' => 'users'
            ));
        }
    }

    public function ProceedPay() {
        echo __METHOD__;
        $params = $this->params['named'];
        $address_id = base64_decode($params['address']);
        $Address = $this->Address->findById($address_id);
        $this->Set('Address', $Address);
        $cart_array = $this->Session->read('cart');
        //pr($cart_array );
        //exit;
        if (isset($cart_array['product_id']) and ($cart_array['product_id'])) {
            foreach ($cart_array['product_id'] as $product_id) {
                $MasterProduct = $this->__get_product_min_price($product_id['Product']['id']);
                if (isset($MasterProduct) and ($MasterProduct)) {
                    $product_condition = $this->_get_product_condition($MasterProduct['conditions']);
                    $cart_array['product_id'][$product_id['Product']['id']]['Product']['condition'] = $product_condition;
                    $cart_array['product_id'][$product_id['Product']['id']]['Product']['MasterProduct'] = $MasterProduct;
                }
            }
            $this->Session->write('cart', $cart_array);
            $cart_array = $this->Session->read('cart');
            $this->Set('cart', $cart_array);
            $session_order_id = $this->Session->read('order_id');
            if (isset($session_order_id) and ($session_order_id)) {
                $this->Set('order_id', $session_order_id);
            } else {
                $price['wondere_get_price'] = 0;
                $merchant_sum = 0;
                $nm = 0;
                foreach ($cart_array['product_id'] as $cart_item) {
                    $coming_seller = $this->Session->read('coming_seller');
                    if (isset($cart_item['Product']['seller_id']) and ($cart_item['Product']['seller_id'])) {
                        if (isset($coming_seller) and ($coming_seller == $cart_item['Product']['seller_id'])) {
                            $price['Seller'][$nm]['Price'] = $price['Seller'][$nm]['Price'];
                        } else {
                            $user_id_of_seller = $this->_get_seller_user_id($cart_item['Product']['seller_id']);

                            $price['Seller'][$nm]['Price'] = 0;

                            $this->Session->write('coming_seller', $cart_item['Product']['seller_id']);

                            $price['Seller'][$nm]['id'] = $cart_item['Product']['seller_id'];
                        }
                    }
                    $cat_percentage = $this->_get_catpercentage($cart_item['Product']['cat_id']);
                    $price['wondere_get_price'] = $price['wondere_get_price'] + ($cart_item['Cart_quantity']
                            *
                            $this->_primary_cal_price($cat_percentage, $cart_item['product_price']));
                    $price['Seller'][$nm]['Price'] = $price['Seller'][$nm]['Price'] + ($cart_item['Cart_quantity'])
                            *
                            ($this->_merchant_cal_price($cat_percentage, $cart_item['product_price']));
                    $nm++;
                }
                $this->Session->delete('coming_seller');
                foreach ($price['Seller'] as $Seller) {
                    $seller_prices[] = $Seller['id'] . '-' . $Seller['Price'];
                }

                $tracking_id = $this->__generateToken('Order', 'tracking_id');
                $this->data['Order']['unique_key'] = $this->__generateToken('Order', 'unique_key');
                ;
                $this->data['Order']['tracking_id'] = $tracking_id;
                $this->data['Order']['customer_id'] = $this->Auth->User('id');
                $this->data['Order']['selllers_prices'] = implode(',', $seller_prices);
                $this->data['Order']['wondere_price'] = $price['wondere_get_price'];
                $this->data['Order']['total_price'] = $cart_array['total_price'];
                $this->data['Order']['payment_status'] = 0;
                $this->data['Order']['shipping_address_id'] = $address_id;
                $this->data['Order']['payment_method'] = 'Authorizenet';

                if (isset($this->data['Order']) and ($this->data['Order'])) {
                    $this->Order->Save($this->data['Order']);
                    $order_id = $this->Order->getLastinsertId();
                    $this->Session->write('order_id', $order_id);

                    $this->_mail_to_customer($this->data['Order']['customer_id'], $cart_array['total_price'], $order_id);

                    $this->Set('order_id', $order_id);
                    foreach ($cart_array['product_id'] as $product_id) {
                        $this->data['OrderItem']['order_id'] = $order_id;
                        $this->data['OrderItem']['order_tracking_id'] = $tracking_id;
                        $this->data['OrderItem']['order_Item_Id'] = $tracking_id = $this->__generateToken('OrderItem', 'order_Item_Id');
                        $this->data['OrderItem']['product_id'] = $product_id['id'];
                        $this->data['OrderItem']['price'] = $product_id['product_price'];
                        $this->data['OrderItem']['qty'] = $cart_item['Cart_quantity'];
                        $this->data['OrderItem']['seller_id'] = $product_id['Product']['seller_id'];

                        $cat_percentage_order_item = $this->_get_catpercentage($product_id['Product']['cat_id']);
                        $this->data['OrderItem']['sell_percentage'] = $cat_percentage_order_item;
                        $this->data['OrderItem']['shipping_address_id'] = $address_id;
                        $this->OrderItem->Save($this->data['OrderItem']);
                        $customer_id = $this->Auth->User('id');
                        $this->_do_order_mail($customer_id, $this->data['OrderItem']['seller_id'], $this->data['OrderItem']['order_Item_Id']);
                    }
                    $amount = $cart_array['total_price'];
                    $this->Set('amount', $amount);
                    $website_url = Configure::read('Website.url');
                    $coffee_store_relay_url = $website_url . "Paypals/Pay/";
                    $this->Set('coffee_store_relay_url', $coffee_store_relay_url);
                }
            }
        } else {
            $this->redirect(array(
                'controller' => 'products',
                'action' => 'cart'
            ));
        }
    }

    public function paypayment() {
        echo __METHOD__;
        //exit;
        if (isset($this->data['Pay']) and ($this->data['Pay'])) {
            $cart_array = $this->Session->read('cart');
            $amount = $cart_array['total_price'];
            //pr($amount);
            //exit;
            require_once getcwd() . '/../vendors/Authorizenet/config.php';
            $METHOD_TO_USE = "AIM";
            if ($METHOD_TO_USE == "AIM") {
                $this->data['Pay']['x_email'] = Configure::read('Website.from_email');
                $order_id = $this->data['Pay']['OrderId'];
                $transaction = new AuthorizeNetAIM;
                $transaction->setSandbox(AUTHORIZENET_SANDBOX);
                $transaction->setFields(array(
                    'amount' => $amount,
                    'card_num' => $this->data['Pay']['x_card_num'],
                    'exp_date' => $this->data['Pay']['x_exp_date'],
                    'first_name' => $this->data['Pay']['x_first_name'],
                    'last_name' => $this->data['Pay']['x_last_name'],
                    'address' => $this->data['Pay']['x_address'],
                    'city' => $this->data['Pay']['x_city'],
                    'state' => $this->data['Pay']['x_state'],
                    'country' => $this->data['Pay']['x_country'],
                    'zip' => $this->data['Pay']['x_zip'],
                    'email' => $this->data['Pay']['x_email'],
                    'card_code' => $this->data['Pay']['x_card_code']
                ));
                $response = $transaction->authorizeAndCapture();

                if ($response->approved) {
                    //pr($response->transaction_id);
                    //exit;
                    // Transaction approved! Do your logic here.
                    $order = $this->Order->findById($order_id);
                    if (isset($order) and ($order)) {
                        $this->data['Order']['id'] = $order['Order']['id'];
                        $this->data['Order']['PayPalTracking'] = $response->transaction_id;
                        $this->data['Order']['PayKey'] = "";
                        $this->data['Order']['invoiceId'] = $response->transaction_id;
                        $this->data['Order']['payment_status'] = 1;
                        $this->Order->Save($this->data['Order']);
                        $id = 1;
                        $this->OrderItem->updateAll(
                                array('OrderItem.payment_status' => "'" . $id . "'"), array('OrderItem.order_id' => $order['Order']['id'])
                        );
                        //exit;
                        $this->Session->delete('cart');
                        $this->Session->delete('order_id');
                        $this->Session->setFlash('Dear user your payment has been successully Paid to Us.');
                    } else {
                        $this->Session->delete('cart');
                        $this->Session->delete('tracking_id');
                        $this->Session->delete('order_id');
                        $this->Session->setFlash('Dear user no record of payment is found in out database. ');
                    }
                } else {
                    $this->Session->delete('cart');
                    $this->Session->delete('tracking_id');
                    $this->Session->delete('order_id');
                    $this->Session->setFlash('' . $response->response_reason_code . '=>' . $response->response_reason_text . '');
                }
                $this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
            }
        }
    }

    function test() {

        echo __METHOD__;
        $params = $this->params['named'];
        $address_id = base64_decode($params['address']);
        $Address = $this->Address->findById($address_id);
        $this->Set('Address', $Address);
        $cart_array = $this->Session->read('cart');
        if (isset($cart_array['product_id']) and ($cart_array['product_id'])) {
            foreach ($cart_array['product_id'] as $product_id) {
                $MasterProduct = $this->__get_product_min_price($product_id['Product']['id']);
                if (isset($MasterProduct) and ($MasterProduct)) {
                    $product_condition = $this->_get_product_condition($MasterProduct['conditions']);
                    $cart_array['product_id'][$product_id['Product']['id']]['Product']['condition'] = $product_condition;
                    $cart_array['product_id'][$product_id['Product']['id']]['Product']['MasterProduct'] = $MasterProduct;
                }
            }
            $this->Session->write('cart', $cart_array);
            $cart_array = $this->Session->read('cart');
            //pr($cart_array);
            //exit;
            $this->Set('cart', $cart_array);
            if (isset($cart_array) and ($cart_array)) {
                $price['wondere_get_price'] = 0;
                $merchant_sum = 0;
                $wonderE_Admin_Id = $this->User->find('first', array('conditions' => 'User.is_admin=1', 'fields' => 'User.id'));
                $wonderE_Admin_Id = $wonderE_Admin_Id['User']['id'];
                $wonderE_Admin_PayPalEmail = $this->_getPayPalEmail($wonderE_Admin_Id);
                $price['wondere_PayPalEmail'] = $wonderE_Admin_PayPalEmail;
                $price['wondere_sum'] = $cart_array['total_price'];
                //exittotal_price;
                $nm = 0;
                foreach ($cart_array['product_id'] as $cart_item) {
                    $coming_seller = $this->Session->read('coming_seller');
                    if (isset($cart_item['Product']['seller_id']) and ($cart_item['Product']['seller_id'])) {
                        if (isset($coming_seller) and ($coming_seller == $cart_item['Product']['seller_id'])) {
                            $price['Seller'][$nm]['Price'] = $price['Seller'][$nm]['Price'];
                        } else {
                            $user_id_of_seller = $this->_get_seller_user_id($cart_item['Product']['seller_id']);
                            $price['Seller'][$nm]['Price'] = 0;
                            $price['Seller'][$nm]['PayPalEmail'] = "";
                            $price['Seller'][$nm]['PayPalEmail'] =
                                    $this->_getPayPalEmail($user_id_of_seller);
                            $this->Session->write('coming_seller', $cart_item['Product']['seller_id']);
                            $price['Seller'][$nm]['id'] = $cart_item['Product']['seller_id'];
                        }
                    }
                    $cat_percentage = $this->_get_catpercentage($cart_item['Product']['cat_id']);
                    $price['wondere_get_price'] = $price['wondere_get_price'] +
                            $this->_primary_cal_price($cat_percentage, $cart_item['product_price']);
                    $price['Seller'][$nm]['Price'] =
                            $price['Seller'][$nm]['Price'] + $this->_merchant_cal_price($cat_percentage, $cart_item['product_price']);
                    $nm++;
                }
                $this->Session->delete('coming_seller');
                $loggged_in_user_id = $this->Auth->User('id');
                $Sender_PayPalEmail = $this->_getPayPalEmail($loggged_in_user_id);
                $price['Sender_PayPalEmail'] = $Sender_PayPalEmail;
            }
            $x = 1;
            $y = date('Y');
            $m = date('m');
            $d = date('d');
            $h = date('h');
            $i = date('i');
            $s = date('s');
            $rand = rand();
            $date = date('i:h:Y:d:m:s') . date('i:h:m:s:Y:d') . date('i:h:Y:d:m:s');
            $date_paypal = base64_encode($date);
            $date_paypal = str_replace('=', "", $date_paypal);
            $date_paypal = substr($date_paypal, 1, 8);
            $this->Set('datedate', $date_paypal);
            $unique_key = $date_paypal;
            foreach ($price['Seller'] as $Seller) {
                $a[$x]['receiverList.receiver(' . $x . ').email'] = $Seller['PayPalEmail'];
                $a[$x]['receiverList.receiver(' . $x . ').amount'] = $Seller['Price'];
                $a[$x]['receiverList.receiver(' . $x . ').primary'] = 0;
                $a[$x]['receiverList.receiver(' . $x . ').invoiceId'] = $unique_key . base64_encode(base64_encode($Seller['id'] * $Seller['id']));
                $seller_prices[] = $Seller['id'] . '-' . $Seller['Price'];
                $x++;
            }
            $tracking_id = $this->__generateToken('Order', 'tracking_id');
            $this->data['Order']['unique_key'] = $unique_key;
            $this->data['Order']['tracking_id'] = $tracking_id;
            //$this->Session->write('tracking_id',$this->data['Order']['tracking_id']);
            $this->data['Order']['customer_id'] = $this->Auth->User('id');
            $this->data['Order']['selllers_prices'] = implode(',', $seller_prices);
            $this->data['Order']['wondere_price'] = $price['wondere_get_price'];
            $this->data['Order']['total_price'] = $cart_array['total_price'];
            $this->data['Order']['payment_status'] = 0;
            $this->data['Order']['shipping_address_id'] = $address_id;
            $this->data['Order']['payment_method'] = 'PayPal';
            if (isset($this->data['Order']) and ($this->data['Order'])) {
                //pr($this->data['Order']);
                //exit;
                $this->Order->Save($this->data['Order']);
                $order_id = $this->Order->getLastinsertId();
                $this->Set('order_id', $order_id);
                foreach ($cart_array['product_id'] as $product_id) {
                    $this->data['OrderItem']['order_id'] = $order_id;
                    $this->data['OrderItem']['order_tracking_id'] = $tracking_id;
                    $this->data['OrderItem']['order_Item_Id'] = $tracking_id = $this->__generateToken('OrderItem', 'order_Item_Id');
                    $this->data['OrderItem']['product_id'] = $product_id['id'];
                    $this->data['OrderItem']['price'] = $product_id['product_price'];
                    $this->data['OrderItem']['qty'] = $cart_item['Cart_quantity'];
                    $this->data['OrderItem']['seller_id'] = $product_id['Product']['seller_id'];

                    $this->data['OrderItem']['shipping_address_id'] = $address_id;
                    $this->OrderItem->Save($this->data['OrderItem']);
                    $customer_id = $this->Auth->User('id');
                    $mail_for_order = $this->_do_order_mail($customer_id, $this->data['OrderItem']['seller_id'], $this->data['OrderItem']['order_Item_Id']);  //exit;	
                }
            }


            $API_AppID = "APP-80W284485P519543T";
            $bodyparams = array(
                "requestEnvelope.errorLanguage" => "en_US",
                "detailLevel" => "ReturnAll",
                "actionType" => "PAY",
                "currencyCode" => "USD",
                'trackingId' => $tracking_id,
                "cancelUrl" => "http://wondere.com/Paypals/paypal_cancel_path", // WonderE Site Cancel Path
                "returnUrl" => "http://wondere.com/Paypals/PayPal_Return_Path",
                "receiverList.receiver(0).email" => $price['wondere_PayPalEmail'], // WonderE Paypal Email Id
                "receiverList.receiver(0).amount" => $price['wondere_sum'], // WonderE get Order amount
                "receiverList.receiver(0).invoiceId" => $unique_key, // WonderE get Order amount
                "receiverList.receiver(0).primary" => true, // WonderE is Primary User
                "feesPayer" => 'PRIMARYRECEIVER',
                "clientDetails.applicationId" => $API_AppID,
                'memo' => 'WonderE_Payment_for_Purchase_Items_On:-' . $date_paypal . '_By_You',
                'senderEmail' => $price['Sender_PayPalEmail'],
                'clientDetails.deviceId' => 'PayPal_Platform_PHP_SDK',
            );
            $x_1 = 1;
            $result = call_User_Func_Array('array_Merge', $a);
            $bodyparams = array_merge((array) $bodyparams, (array) $result);
            //pr($bodyparams);
            //exit;
            $this->Set('bodyparams', $bodyparams);
        } else {
            $this->redirect(array('controller' => 'products', 'action' => 'cart'));
        }
    }

    public function paypal_cancel_path() {
        echo __METHOD__;
        $this->Session->delete('cart');
        $this->Session->delete('tracking_id');
        $this->Session->delete('payKey');
        $this->Session->setFlash('Dear user Payment has been cancelled By you.');
        $this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
    }

    public function PayPal_Return_Path() {
        echo __METHOD__;
        $current_directory = getcwd();
        $new_app = $current_directory;
        require_once $current_directory . '/../vendors/AdaptivePayments/lib/AdaptivePayments.php';
        require_once $current_directory . '/../vendors/AdaptivePayments/lib/Stub/AP/AdaptivePaymentsProxy.php';
        $payKey = $this->Session->read('payKey');
        if (isset($payKey) and ($payKey)) {
            try {
                $payKey = $this->Session->read('payKey');
                //echo $payKey;
                $pdRequest = new PaymentDetailsRequest();
                $pdRequest->payKey = $payKey;
                $rEnvelope = new RequestEnvelope();
                $rEnvelope->detailLevel = "ReturnAll";
                $rEnvelope->errorLanguage = "en_US";
                $pdRequest->trackingId = $this->Session->read('tracking_id');
                $pdRequest->requestEnvelope = $rEnvelope;
                $ap = new AdaptivePayments();
                $response = $ap->PaymentDetails($pdRequest);
                // pr($response);
                //exit;
                $string = $response->memo;
                //pr($string);
                //exit;
                $explode_dat = explode("-", $string);

                unset($explode_dat[0]);
                $explode_dat = explode("_", $explode_dat[1]);
                $unique_key = $explode_dat[0];
                if (isset($response->status) and ($response->status == "CREATED")) {
                    //$UniqueInvoiceOrderId = $response->paymentInfoList->paymentInfo[0]->receiver->invoiceId;
                    $order = $this->Order->findByUniqueKey($unique_key);
                    //pr($order);
                    //exit;
                    if (isset($order) and ($order)) {
                        $this->data['Order']['id'] = $order['Order']['id'];
                        $this->data['Order']['PayPalTracking'] = $response->trackingId;
                        $this->data['Order']['PayKey'] = $response->payKey;
                        $this->data['Order']['invoiceId'] = $response->paymentInfoList->paymentInfo[0]->receiver->invoiceId;
                        $this->data['Order']['payment_status'] = 1;
                        $this->Order->Save($this->data['Order']);
                        $id = 1;
                        $this->OrderItem->updateAll(
                                array('OrderItem.payment_status' => "'" . $id . "'"), array('OrderItem.order_id' => $order['Order']['id'])
                        );
                        //exit;
                        $this->Session->delete('cart');
                        $this->Session->delete('payKey');
                        $this->Session->setFlash('Dear user your payment has been successully Paid to Us.');
                    } else {
                        $this->Session->delete('cart');
                        $this->Session->delete('tracking_id');
                        $this->Session->delete('payKey');
                        $this->Session->setFlash('Dear user no record of payment is found in out database. ');
                    }
                }
                if (strtoupper($ap->isSuccess) == 'FAILURE') {
                    $_SESSION['FAULTMSG'] = $ap->getLastError();
                    $this->Session->delete('cart');
                    $this->Session->delete('tracking_id');
                    $this->Session->delete('payKey');
                    $this->Session->setFlash('Dear user FAILURE Error FAILURE Ocuur during Payment From Paypal.');
                }
            } catch (Exception $ex) {

                $fault = new FaultMessage();
                $errorData = new ErrorData();
                $errorData->errorId = $ex->getFile();
                $errorData->message = $ex->getMessage();
                $fault->error = $errorData;
                $_SESSION['FAULTMSG'] = $fault;
                $this->Session->delete('tracking_id');
                $this->Session->delete('payKey');
                $this->Session->delete('cart');
                $this->Session->setFlash('Dear user FAILURE Error catch Ocuur during Payment From Paypal.');
            }
            $this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
        }
    }

    function PaymentSettings() {
        echo __METHOD__;
        $user_id = $this->Auth->User('id');
        $paypal_registred = $this->_is_paypal_registred($user_id);
        $this->Set('paypal_registred', $paypal_registred);
    }

    function PaymentInfo() {
        echo __METHOD__;
        $user_id = $this->Auth->User('id');
        $paypal_registred = $this->_is_paypal_registred($user_id);
        $this->Set('paypal_registred', $paypal_registred);
    }

}